#include <stdio.h>
#include <string.h>

#include "mqtt_task.h"
#include "timestamp.h"
#include "log.h"

#include <glib.h>
#include <mosquitto.h>

gpointer mqtt_pub_task(gpointer data);

static GThread*     mqtt_pub_task_h = NULL;

static struct mosquitto*    mqtt_client;

#define SERVER_ADDRESS  "localhost"
#define SERVER_PORT     1883
#define CLIENTID        "XiamenPWSInside"
#define TOPIC           "Xiamen/PWS"
#define QOS             1
#define TIMEOUT         10000L

void onConnect(struct mosquitto *mosq, void *obj, int result)
{
    log_print(LOG_INFO, "MQTT server connected.");
}

void onDisconnect(struct mosquitto *mosq, void *obj, int result)
{
    log_print(LOG_ERROR, "MQTT server disconnected, reason:%d", result);
}

void onPublish(struct mosquitto *mosq, void *obj, int mid)
{

}


void mqttInit()
{
    int     rc, major, minor, rev;;

    mosquitto_lib_init();

    rc = mosquitto_lib_version(&major, &minor, &rev);
    log_print(LOG_INFO, "mosquitto library: %d.%d.%d", major, minor, rev);

    mqtt_client = mosquitto_new(CLIENTID, false, NULL);

    mosquitto_connect_callback_set(mqtt_client, onConnect);
    mosquitto_publish_callback_set(mqtt_client, onPublish);
    mosquitto_disconnect_callback_set(mqtt_client, onDisconnect);

    mosquitto_connect(mqtt_client, SERVER_ADDRESS, SERVER_PORT, 60);

    mqtt_pub_task_h = g_thread_new("MQTT Pub thread", mqtt_pub_task, NULL);
}

void mqtt_publish_ht(const WS_DATA_IN* data)
{
    char        wsDataJson[100];
    int         pos = 0;
    char        timestamp_s[30];

    getTimestamp(timestamp_s, sizeof(timestamp_s));
    pos = snprintf(wsDataJson, sizeof(wsDataJson), "{\"t\":\"%s\",", timestamp_s);
    pos += snprintf(wsDataJson + pos, sizeof(wsDataJson) - pos, "\"iT\":%d.%01d,", data->temperature / 10, data->temperature % 10);
    pos += snprintf(wsDataJson + pos, sizeof(wsDataJson) - pos, "\"iH\":%d.%01d}", data->humidity / 10, data->humidity % 10);

    mosquitto_publish(mqtt_client, NULL, TOPIC, pos, wsDataJson, 0, 0);
}

void mqtt_publish_bat(const WS_DATA_IN_BAT* data)
{
    char        wsDataJson[100];
    int         pos = 0;
    char        timestamp_s[30];

    getTimestamp(timestamp_s, sizeof(timestamp_s));
    pos = snprintf(wsDataJson, sizeof(wsDataJson), "{\"t\":\"%s\",", timestamp_s);
    pos += snprintf(wsDataJson + pos, sizeof(wsDataJson) - pos, "\"iBp\":%d}", data->battery);

    mosquitto_publish(mqtt_client, NULL, TOPIC, pos, wsDataJson, 0, 0);
}

gpointer mqtt_pub_task(gpointer data)
{
    mosquitto_loop_forever(mqtt_client, 100, 1);
}
